function fn(nums) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(nums * 2)
      }, 1000)
    })
  }
  
  function* gen() {
    const num1 = yield fn(1)
    console.log(num1);
    const num2 = yield fn(num1)
    console.log(num2);
    const num3 = yield fn(num2)
    console.log(num3);
    return num3
  }
  
  function generatorToAsync(generatorFn) {
    return function() {
      const gen = generatorFn.apply(this, arguments) // gen有可能有参数
  
      return new Promise((resolve, reject) => {
  
        function go(key, arg) {
          let res;
          try {
            res = gen[key](arg) // 有可能执行返回的reject状态的Promise
          } catch (error) {
            return reject(error)
          }
  
          const { value, done } = res
          if (done) {
            return resolve(value)
          } else {
            return Promise.resolve(value).then(
              val => go('next', val),
              err => go('throw', err)
            )
          }
        }
  
        go('next')
  
        // const g = generatorFn()
        // const next1 = g.next()
        // next1.value.then(res1 => {
  
        //   const next2 = g.next(res1)
        //   next2.value.then(res2 => {
  
        //     const next3 = g.next(res2)
        //     next3.value.then(res3 => {
  
        //       resolve(g.next(res3).value)
        //     })
        //   })
        // })
      })
    }
  }
  
  
  
  const genToAsync = generatorToAsync(gen)
  const asyncRes = genToAsync()
  console.log(asyncRes); // Promise
  asyncRes.then(res => console.log(res))
  